(function($) {
  if (!$) {
    console.log("引用的时，必须先引用mui.min.js！!!");
  }
  var DB = function() {
    this.dbName = 'mqms' // 数据库名称
    this.dbPath = '_doc/mqms.db' // 数据库地址,推荐以下划线为开头   _doc/xxx.db
    // 判断数据库是否打开
    this.isOpen = function() {
      // 数据库打开了就返回 true,否则返回 false
      var open = plus.sqlite.isOpenDatabase({
        name: this.dbName, // 数据库名称
        path: this.dbPath // 数据库地址
      })
      return open;
    }

    // 创建数据库 或 有该数据库就打开
    this.openSqlite = function() {
      return new Promise((resolve, reject) => {
        // 打开数据库
        if (this.isOpen()) {
          resolve('已经打开')
        }
        plus.sqlite.openDatabase({
          name: this.dbName,
          path: this.dbPath,
          success(e) {
            resolve(e); // 成功回调
          },
          fail(e) {
            reject(e); // 失败回调
          }
        })
      })
    }

    // 关闭数据库
    this.closeSqlite = function() {
      return new Promise((resolve, reject) => {
        plus.sqlite.closeDatabase({
          name: this.dbName,
          success(e) {
            resolve(e);
          },
          fail(e) {
            reject(e);
          }
        })
      })
    }
    // 数据库建表 格式
    this.createFormat = function(dbTable, obj, mainKey) {
      let open = this.isOpen()
      if (open) {
        let str = []
        for (key in obj) {
          if (key != mainKey) {
            str.push(`"${key}" text`)
          }
        }
        str.join(',')
        let data = `"${mainKey}" text PRIMARY KEY,${str}`
        this.createTable(dbTable, data)
      }
    }
    // 数据库建表 sql:'CREATE TABLE IF NOT EXISTS dbTable("id" varchar(50),"name" TEXT) 
    // 创建 CREATE TABLE IF NOT EXISTS 、 dbTable 是表名，不能用数字开头、括号里是表格的表头
    this.createTable = function(dbTable, data) {
      return this.executeListSQL(`CREATE TABLE IF NOT EXISTS ${dbTable}(${data})`)
    }

    // 数据库删表 sql:'DROP TABLE dbTable'
    this.dropTable = function(dbTable) {
      return this.executeListSQL(`DROP TABLE ${dbTable}`)
    }

    // 向表格里添加数据 sql:'INSERT INTO dbTable VALUES('x','x','x')'   对应新增
    // 或者 sql:'INSERT INTO dbTable ('x','x','x') VALUES('x','x','x')'   具体新增
    // 插入 INSERT INTO  、 dbTable 是表名、根据表头列名插入列值
    this.insertTableData = function(dbTable, data, condition) {
      console.log(typeof data, data)
      console.log(typeof condition, condition)
      let str = ''
      // 判断有没有传参
      if (dbTable !== undefined && data !== undefined) {
        // 判断传的参是否有值
        var bol = (JSON.stringify(data) == "{}");
        if (!bol) {
          if (condition == undefined) {
            str = `INSERT INTO ${dbTable} VALUES('${data}')`;
          } else {
            str = `INSERT INTO ${dbTable} (${condition}) VALUES(${data})`;
          }
          // console.log(str);
          return this.executeListSQL(str)
        } else {
          return new Promise((resolve, reject) => {
            reject("错误添加")
          })
        }
      } else {
        return new Promise((resolve, reject) => {
          reject("错误添加")
        })
      }
    }
    // 根据条件向表格里添加数据  有数据更新、无数据插入  格式化sql语句
    this.insertOrReplace = function(dbTable, obj) {
      let open = this.isOpen()
      if (open) {
        let sql = []
        let condition = []
        for (key in obj) {
          sql.push(`'${obj[key]}'`)
          condition.push(`'${key}'`)
        }
        let data = `${sql.join(',')}`
        let conditionStr = `${condition.join(',')}`
        this.insertOrReplaceData(dbTable, data, conditionStr)
      }
    }
    // 根据条件向表格里添加数据  有数据更新、无数据插入
    // (建表时需要设置主键) 例如 --- "roomid" varchar(50) PRIMARY KEY
    this.insertOrReplaceData = function(dbTable, data, condition) {
      // 判断有没有传参
      let str = ''
      if (dbTable !== undefined && data !== undefined) {
        if (condition == undefined) {
          str = `INSERT OR REPLACE INTO ${dbTable} VALUES('${data}')`;
        } else {
          str = `INSERT OR REPLACE INTO ${dbTable} (${condition}) VALUES(${data})`;
        }
        // console.log(str);
        return this.executeListSQL(str)
      } else {
        return new Promise((resolve, reject) => {
          reject("错误添加")
        })
      }
    }

    // 查询获取数据库里的数据 sql:'SELECT * FROM dbTable WHERE lname = 'lvalue''
    // 查询 SELECT * FROM 、 dbTable 是表名、 WHERE 查找条件 lname,lvalue 是查询条件的列名和列值
    this.selectTableData = function(dbTable, dataArr) {
      if (dbTable !== undefined) {
        var sql = `SELECT * FROM ${dbTable}`
        if (Array.isArray(dataArr)) {
          dataArr.forEach((item, i) => {
            if (i == 0) {
              sql +=
                ` WHERE ${item.key} ${item.has? 'Like':'='} '${item.has? "%":""}${item.value}${item.has? "%":""}'`
            } else {
              sql += ' AND '
              sql +=
                `${item.key} ${item.has? 'Like':'='} '${item.has? "%":""}${item.value}${item.has? "%":""}'`
            }
          })
        }
        console.log(sql)
        return new Promise((resolve, reject) => {
          // 表格查询数据  执行查询的SQL语句
          plus.sqlite.selectSql({
            name: this.dbName,
            sql: sql,
            success(e) {
              resolve(e);
            },
            fail(e) {
              reject(e);
            }
          })
        })
      } else {
        return new Promise((resolve, reject) => {
          reject("错误查询")
        });
      }
    }

    // 删除表里的数据 sql:'DELETE FROM dbTable WHERE lname = 'lvalue''
    // 删除 DELETE FROM 、 dbTable 是表名、 WHERE 查找条件 lname,lvalue 是查询条件的列名和列值
    this.deleteTableData = function(dbTable, lname, lvalue, ww, ee) {
      let str = ''
      if (dbTable !== undefined) {
        if (lname == undefined) {
          str = `DELETE FROM ${dbTable}`;
        } else {
          if (ww !== undefined) {
            // 两个检索条件
            str = `DELETE FROM ${dbTable} WHERE ${lname} = '${lvalue}' AND ${ww} = '${ee}'`;
          } else {
            // 一个检索条件
            str = `DELETE FROM ${dbTable} WHERE ${lname} = '${lvalue}'`;
          }
        }
        return this.executeListSQL(str)
      } else {
        return new Promise((resolve, reject) => {
          reject("错误删除")
        });
      }
    }

    // 修改数据表里的数据 sql:"UPDATE dbTable SET 列名 = '列值',列名 = '列值' WHERE lname = 'lvalue'"
    // 修改 UPDATE 、 dbTable 是表名, data: 要修改的列名=修改后列值, lname,lvalue 是查询条件的列名和列值
    this.updateTableData = function(dbTable, data, lname, lvalue) {
      let str = ''
      if (lname == undefined) {
        str = `UPDATE ${dbTable} SET ${data}`;
      } else {
        str = `UPDATE ${dbTable} SET ${data} WHERE ${lname} = '${lvalue}'`;
      }
      // WHERE 前面是要修改的列名、列值，后面是条件的列名、列值
      return this.executeListSQL(str)
    }

    // 获取指定数据条数  sql:"SELECT * FROM dbTable ORDER BY 'id' DESC LIMIT 15 OFFSET 'num'"
    // dbTable 表名, ORDER BY 代表排序默认正序, id 是排序的条件 DESC 代表倒序，从最后一条数据开始拿
    // LIMIT 15 OFFSET '${num}',这句的意思是跳过 num 条拿 15 条数据, num 为跳过多少条数据是动态值
    // 例 初始num设为0，就从最后的数据开始拿15条，下次不拿刚获取的数据，所以可以让num为15，这样就能一步一步的拿完所有的数据
    this.pullSQL = function(dbTable, id, num) {
      return new Promise((resolve, reject) => {
        plus.sqlite.selectSql({
          name: this.dbName,
          sql: `SELECT * FROM ${dbTable} ORDER BY '${id}' DESC LIMIT 15 OFFSET '${num}'`,
          success(e) {
            resolve(e);
          },
          fail(e) {
            reject(e);
          }
        })
      })
    }

    this.addColumn = function(dbTable, columnName) {
      let dbName = this.dbName
      return new Promise((resolve, reject) => {
        plus.sqlite.selectSql({
          name: dbName,
          sql: `select * from sqlite_master where name='${dbTable}'`,
          success(e) {
            console.log("eeee", e)
            if (e.length == 0) {
              //表不存在  不用新增
              console.log("表不存在  不用新增")
              resolve(e);
            } else {
              plus.sqlite.selectSql({
                name: dbName,
                sql: `PRAGMA table_info(${dbTable})`,
                success(e) {
                  console.log("表里所有字段", e)
                  let isHas = false
                  for (let i = 0; i < e.length; i++) {
                    if (e[i].name == columnName) {
                      isHas = true
                    }
                  }
                  if (isHas) {
                    console.log("字段存在  不用新增")
                    resolve(e);
                  } else {
                    plus.sqlite.selectSql({
                      name: dbName,
                      sql: `ALTER TABLE ${dbTable} ADD COLUMN ${columnName} Text`,
                      success(e) {
                        console.log("新增成功", e)
                        resolve(e);
                      },
                      fail(e) {
                        reject(e);
                      }
                    })
                  }
                },
                fail(e) {
                  reject(e);
                }
              })
            }

          },
          fail(e) {
            console.log("eeerrre", e)
            reject(e);
          }
        })

        ;
      })
    }

    this.executeListSQL = function(baseSql) {
      return new Promise((resolve, reject) => {
        // 修改表数据
        plus.sqlite.executeSql({
          name: this.dbName,
          sql: baseSql,
          success(e) {
            resolve(e);
          },
          fail(e) {
            reject(e);
          }
        })
      })
    }
  }
  $.DB = new DB();
})(mui);
